<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesScanRecordDefectiveTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="$t('mesScanRecordDefective.createReviewOrder')"
    >
    </ele-form-drawer>
    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$i18n.t('mesScanRecordDefective.importUsers')"
    >
      <template v-slot:file="{ desc, data, field, formData }">
        <!-- 插槽内容有el-form-item组件包裹 -->
        <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto" />
      </template>
    </ele-form-drawer>
  </div>
</template>

<script>
import {
  operateList,
  searchConfig,
  importFormDescDialog,
  formDescDialog,
  rowConfig,
} from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  createReview,
  rowDetail,
  importData,
  mesDefectiveReview,
  getIsReviewList,
} from "@/api/record/mesScanRecordDefective";
import uploadNoAuto from "@/components/upload-no-auto";
import { uniqueKey, popover } from "@/utils/judge.js";
export default {
  name: "mesScanRecordDefective",
  components: {
    uploadNoAuto,
  },
  data() {
    const _this = this;
    return {
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      searchConfig,
      operateList,
      getList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },
        // {
        //   prop: "barcode",
        //   label: "条码",
        //   fixed: "left",
        //   minWidth: 150,
        //   showOverflowTooltip: true,
        // },
        {
          prop: "orderCode",
          label: $i18n.t("mesScanRecordDefective.orderCode"),
          fixed: "left",
          minWidth: 220,
          showOverflowTooltip: true,
        },
        {
          prop: "lineName",
          label: $i18n.t("common.lineName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "productProcessCode",
          label: $i18n.t("common.processCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "productProcessName",
          label: $i18n.t("common.processName"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesScanRecordDefective.prodCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesScanRecordDefective.prodName"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesCode",
          label: $i18n.t("mesScanRecordDefective.seriesCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesName",
          label: $i18n.t("mesScanRecordDefective.seriesName"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentCode",
          label: $i18n.t("mesScanRecordDefective.equipmentCode"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentName",
          label: $i18n.t("mesScanRecordDefective.equipmentName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "faultCode",
          label: $i18n.t("mesScanRecordDefective.faultCode"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "faultName",
          label: $i18n.t("mesScanRecordDefective.faultName"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "quantity",
          label: $i18n.t("mesScanRecordDefective.quantity"),
          // minWidth: 130,
          showOverflowTooltip: true,
        },

        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 160,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 160,
        },
        {
          prop: "isInvalid",
          label: $i18n.t("mesScanRecordDefective.invalidRecord"),
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getIsReviewList();
            return list.data.result;
          },
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "isReview",
          label: $i18n.t("mesScanRecordDefective.isReview"),
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getIsReviewList();
            return list.data.result;
          },
          minWidth: 180,
          showOverflowTooltip: true,
          fixed: "right",
        },
        {
          prop: "reviewCode",
          label: $i18n.t("mesScanRecordDefective.reviewCode"),
          minWidth: 160,
          showOverflowTooltip: true,
          fixed: "right",

          render: (h, { row }) => {
            //  href={`mom/review/mesDefectiveReview?reviewCode=${row.reviewCode}`}

            return popover(row.reviewCode, h, "", () => {
              _this.$router.push({
                path: "/review/mesDefectiveReview",
                query: { reviewCode: row.reviewCode },
              });
            });

            // return (

            //   <el-link
            //     on={{
            //       click: () => {
            //         _this.$router.push({
            //           path: "/review/mesDefectiveReview",
            //           query: { reviewCode: row.reviewCode }
            //         })
            //       }
            //     }}
            //     type="primary">
            //     {row.reviewCode}
            //   </el-link>
            // )
          },
        },
        // {
        //   prop: "operate",
        //   label: "操作",
        //   width: 160,
        //   fixed: "right",
        //   render: (h, scope) => {
        //     return (
        //       <ele-row-operation
        //         scope={scope}
        //         rowConfig={rowConfig}
        //         onRowOperate={this.rowOperate}
        //       />
        //     );
        //   },
        // },
      ],
    };
  },
  computed: {},
  methods: {
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        createReview: () => {
          let flag = true; //是否通过
          data.rows.forEach((element) => {
            if (element.isInvalid == 1) {
              flag = false;
            }
          });
          if (!flag) {
            this.$message.warning(
              $i18n.t("mesScanRecordDefective.limitInvalid")
            );
            return;
          }
          let list1 = uniqueKey(data.rows, "orderCode");
          let list2 = uniqueKey(data.rows, "seriesCode");
          let list3 = uniqueKey(data.rows, "productProcessCode");

          let list4 = uniqueKey(data.rows, "equipmentCode");

          let list5 = uniqueKey(data.rows, "faultCode");

          let list6 = uniqueKey(data.rows, "isReview");
          if (list1.length > 1) {
            this.$message.warning($i18n.t("mesScanRecordDefective.limitOrder"));
            return;
          }
          if (list2.length > 1) {
            this.$message.warning(
              $i18n.t("mesScanRecordDefective.limitSeries")
            );
            return;
          }
          if (list3.length > 1) {
            this.$message.warning(
              $i18n.t("mesScanRecordDefective.limitProcess")
            );
            return;
          }
          if (list4.length > 1) {
            this.$message.warning($i18n.t("mesScanRecordDefective.limitEqu"));
            return;
          }
          if (list5.length > 1) {
            this.$message.warning(
              $i18n.t("mesScanRecordDefective.selectBadClassification")
            );
            return;
          }
          if (list6.length > 1 || list6[0].isReview == 1) {
            this.$message.warning(
              $i18n.t("mesScanRecordDefective.selectUnReview")
            );
            return;
          }
          this.$confirm(
            $i18n.t("mesScanRecordDefective.confirmMsg"),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.visible = true;
            this.formDataDialog = list1[0];

            this.formDataDialog.defectiveIdList = data.rows.map(
              (ite) => ite.id
            );
            this.formDataDialog.rejectQuantity = data.rows.reduce(
              (sum, e) => sum + Number(e.quantity || 0),
              0
            );

            console.log(1111, this.formDataDialog.rejectQuantity);
          });
        },
        import: () => {
          this.importDialogData = {};
          this.importVisible = true;
        },
      };
      fnc[data.handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
        },
      };
      fnc[handleName]();
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      const params = {
        title: $i18n.t("common.addSuccess"),
        api: mesDefectiveReview,
        data,
      };
      this.doSubmit(params);
    },
    //生成评审单
    createReview(data) {
      this.loading = true;
      createReview(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(
            message ||
              $i18n.t("mesScanRecordDefective.successfullyGenerateReviewList")
          );
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, "file", file);
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t("common.uploadMsg"));
        return;
      }
      const formData = new FormData();
      formData.append("file", this.importData.file.get("file"));
      this.isLoadingImport = true;
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t("common.importSuccess"));
          this.isLoadingImport = false;
          this.importVisible = false;
          this.refresh();
        })
        .catch((error) => {
          console.log("错误", error);
          this.$set(this.importData, "file", null);
        })
        .finally(() => {
          this.isLoadingImport = false;
          this.$refs.uploadNoAuto.clearFiles();
        });
    },
  },
};
</script>
